package com.haizhi.crm.sys.auth.service.impl;

import com.haizhi.crm.common.constant.SysStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.log.GLog;
import com.haizhi.crm.common.log.LogFactory;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.sys.auth.dao.ResourceDao;
import com.haizhi.crm.sys.auth.model.ResourceDo;
import com.haizhi.crm.sys.auth.model.ResourceVo;
import com.haizhi.crm.sys.auth.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangyijun on 2018/5/17.
 */
@Service
public class ResourceServiceImpl implements ResourceService {
    private static final GLog LOG = LogFactory.getLogger(ResourceServiceImpl.class);

    @Autowired
    private ResourceDao resourceDao;

    @Override
    public Response findAll() {
        try {
            return Response.success(getResourceVos());
        } catch (Exception e) {
            LOG.error("search resource list error", e);
            throw new UnexpectedStatusException(SysStatus.FIND_RESOURCE_LIST_ERROR, e);
        }

    }

    private List<ResourceVo> getResourceVos() {
        List<ResourceDo> resourceDos = resourceDao.findAll();
        return ResourceVo.buildResourceTreeFromDo(resourceDos);
    }

    @Override
    public Response findForRelationPermission() {
        List<ResourceVo> resourceVos = getResourceVos();

        List<ResourceVo> resources = new ArrayList<>();
        resourceVos.forEach(resourceVo -> {
            if ("客户详情".equals(resourceVo.getName())) {
                resources.add(resourceVo);
            }
        });
        return Response.success(resources);
    }
}
